#! python3.11
import os
from FileAutoZip_Core_V1_1 import log_folder_dirs as LFD


class locker:

    def __init__(self, root_path: str):
        self.root_path = root_path
        self.working = self.root_path + "\\Archiving_By_Yingestech.txt"
        self.check = self.__check_or_create()

    def __check_or_create(self):
        if os.path.exists(self.working):
            try:
                os.remove(self.working)
            except:
                return False
        with open(self.working, 'a+', encoding='utf-8') as fs:
            fs.write(
                "If this file representation that the archiving activity is working!!!--By Yingestech"
            )
        self.open_working = open(self.working)
        return True

    def release(self):
        if self.check:
            self.open_working.close()
            os.remove(self.working)


def AAmain(log_root_dir: str,
           clean_remain: int,
           logs_Remain: int,
           zips_in_one_time: int = 5):
    """AA Main

    Args:
        log_root_dir (_type_): Root Folder of logs
        clean_remain (_type_): Clean time Seconds
        logs_Remain (_type_): Archive Time Seconds
        zips_in_one_time (int, optional): To zip qty. Defaults to 5.
    """

    if zips_in_one_time < 0:
        print("Error:'zips_in_one_time'<0,Please Reset")
        return
    lock = locker(log_root_dir)
    if not lock.check:
        print("Another process is working! Please try it later!")
        return

    # Get the list folder
    folder_lists = LFD(log_root_dir, 4, 2)
    # Clean Sweep folder
    print("Start to clean Sweep folder...")
    (cleaned, skipped,
     allc) = folder_lists.clean_folders(clean_remain,
                                        ['', 'Sweep_[1-9]+', '([^\s]+\.bmp)$'],
                                        1)
    if cleaned > 0:
        print(
            "Cleaned %s parts folder with Sweep remain for more then %.2f mins"
            % (cleaned, (clean_remain / 60)))
    elif cleaned == 0:
        print("No sweep folder to delete")
    if skipped > 0:
        print(" %s skipped with time or delete issue" % skipped)
    if zips_in_one_time == 0 and cleaned >= 0:
        print("zips_in_one_time = 0,No zip task!")
    elif cleaned >= 0:
        archived = folder_lists.sevenzips(logs_Remain, zips_in_one_time)
        if archived == -1:
            print("Error occured,archive process stopped")
        elif archived == -2:
            print(
                "Another archiving process is working! Please try it later\n")
        elif archived == 0:
            print("No file ready to archive!")
        else:
            print("%s files archived successfully!" % archived)
    lock.release()


if __name__ == "__main__":
    log_root_dir = r'C:\Users\tding1\Desktop\TestResults'
    AAmain(log_root_dir, 10, 11, 1)
